<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

class m_website_actions_AjaxSaveStructureAction extends m_backoffice_extends_Action
{
	public function execute()
	{
		$parameters = $this->getRequest()->getParameters();
		
		$documentId = $this->getRequest()->getParameter('pageId');
		$documentLang = $this->getRequest()->getParameter('pageLang');
		
		$tempDocService = m_backoffice_services_TempDocService::getInstance();
		
		if($tempDocService->hasTemporary($documentId, $documentLang))
		{
			$page = $tempDocService->getTemporaryDocument($documentId, $documentLang);
		}
		else
		{
			$page = f_document_Provider::getInstance()->getByModelAndUniqueId('website/Page', $documentId, $documentLang);			
		}
		
		$blocks = $page->getAllBlocks();

		foreach($parameters as $key => $parameter)
		{
			if(strstr($key, "freeContent"))
			{
				foreach($parameter as $blockDivId)
				{
					$blockId = str_replace("block_", "", $blockDivId);
					if(isset($blocks[$blockId]))
					{
						$result[$key][] = $blocks[$blockId];
					}
				}
			}
		}
		
		if(isset($result))
		{
			$res = $page->formatTemplate($result);		
			$page->setContent($res);
		}
		
		$tempDocService->saveTemporaryDocument($page);
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("backoffice_accessBo", "website_TabPageStructure"));
	}

	public function errorHandler()
	{
		return null;
	}
}